package com.dorm.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.dorm.common.Result;
import com.dorm.entity.User;
import com.dorm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    /**
     * 登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> params) {
        String username = params.get("username");
        String password = params.get("password");

        String token = userService.login(username, password);
        User user = userService.getByUsername(username);

        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("user", user);

        return Result.success(data);
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    public Result<User> getUserInfo(@RequestAttribute Long userId) {
        User user = userService.getById(userId);
        user.setPassword(null); // 不返回密码
        return Result.success(user);
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success("退出成功");
    }

    /**
     * 注册（仅用于测试）
     */
    @PostMapping("/register")
    public Result<String> register(@RequestBody User user) {
        // 检查用户名是否已存在
        if (userService.getByUsername(user.getUsername()) != null) {
            return Result.error("用户名已存在");
        }

        // 密码加密
        user.setPassword(DigestUtil.md5Hex(user.getPassword()));
        user.setStatus(1);
        user.setRole("admin");

        userService.save(user);
        return Result.success("注册成功");
    }
}

